import { BaseRequest } from '@/core'
import { buildFullPath, merge, transformGetUrl } from '@/core/util'
import { CallbackResult, RequestConfig, ResponseResult } from './type'
import { getCredentials } from './util'

class Request extends BaseRequest<RequestConfig, ResponseResult> {
    protected dispatchRequest(config: RequestConfig): Promise<ResponseResult> {
        return new Promise((resolve, reject) => {
            const {
                baseUrl,
                url = '',
                responseType = 'text',
                dataType = 'json',
                headers,
                params = {},
                method = 'GET',
                withCredentials,
                credentials,
                ...options
            } = merge({}, { ...config }) as RequestConfig
            const newUrl = buildFullPath(url, baseUrl)
            const httpUrl = method === 'GET' ? transformGetUrl(url, params) : newUrl
            wx.request({
                url: httpUrl,
                data: params,
                method: method,
                dataType,
                responseType,
                header: headers,
                credentials: getCredentials(withCredentials, credentials),
                success(response: Record<string, any>) {
                    const { data, statusCode, cookies, errMsg } = { ...response } as Record<
                        string,
                        any
                    >
                    resolve({
                        data,
                        status: statusCode,
                        headers: headers,
                        statusText: errMsg,
                        cookies,
                        config: config
                    })
                },
                fail(error: CallbackResult) {
                    reject(error.errMsg)
                },
                ...options
            } as any)
        })
    }
}

export default Request
